import { message, Modal, notification } from "ant-design-vue";
import defaultSetting from "./defaultSetting";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { createVNode, h } from "vue";
import store from "../../store";
import * as storage from "./storage";
// import BLCOMMON from "bl-common-vue3";
import { L } from "../../locale";
import * as cheerio from "cheerio";
import {
  storyConfigGet,
  textConfigGet,
  aiTextGet,
  humanConfigGet,
  videoConverTextConfig,
  consumptionPointRule,
  oneclickPreviewNum
} from "@/common/server/configGet.js";
import imgErr from '../image/shotstack/imgErr.png'
// 获取视频组纯文本方法
import { getAllText } from "@/common/utils/richTextProcessing";

const toString = Object.prototype.toString;

let BASE_URL = defaultSetting.requestDomain;

if (process.env.NODE_ENV === "development") {
  BASE_URL = BASE_URL + "/api";
}

const utils = {
  // 图片上传的地址
  imgAction: BASE_URL + "/public/system/uploadImage",
  sendImg: BASE_URL + "/public/system/uploadImage",
  excelAction: BASE_URL + "/work_ai/user/text/import",
  fileAction: BASE_URL + "/public/system/uploadFile",
  NewfileAction: BASE_URL + "/work_ai/material/upload",
  // 数字验证正则
  numberReg: /^\d+(\.\d+)?$/,
  // 手机号正则
  phoneReg: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,

  // staticPath:
  //   (defaultSetting.requestDomain || "https://local.kuaijingai.com") +
  //   "/public_web/static/",
  staticPath:
  (defaultSetting.requestDomain || "https://montage.chocei.com") +
  "/public_web/static/",

  urlReg: /(http|https):\/\/([\w.]+\/?)\S*/,

  /**
   * @description: 数组合并并去重
   * @param {Array} arr1
   * @param {Array} arr2
   * @return {Array} arr
   */
  combineArr: (arr1, arr2) => {
    let arr = [...arr1, ...arr2];
    return Array.from(new Set(arr));
  },

  /**
   * @description: 确认弹窗（删除确认） 重写是为了多语言
   * @param {*} 同ant design api
   */
  modalConfirm: ({
    title = "提示",
    content = {},
    centered = true,
    okText = "确定",
    cancelText = "取消",
    onOk,
    onCancel,
    okType = "primary",
  }) => {
    store.dispatch("modalConfirm", {
      title: () => title,
      content: () => content,
      okText,
      icon: () => createVNode(ExclamationCircleOutlined),
      okType,
      cancelText,
      centered,
      onOk() {
        onOk && onOk();
      },
      onCancel() {
        onCancel && onCancel();
      },
    });
    // const modal = Modal.confirm({
    //   title: () => title,
    //   content: () => content,
    //   okText,
    //   icon: () => createVNode(ExclamationCircleOutlined),
    //   okType,
    //   cancelText,
    //   centered,
    //   onOk() {
    //     onOk && onOk();
    //   },
    //   onCancel() {
    //     onCancel && onCancel();
    //   },
    // });
  },

  /**
   * @description: 表单验证为数字
   * @param {Object} rules 规则
   * @param {*} value 值
   */
  numberValidator: async (rules, value) => {
    // console.log("rules,value", rules, value);
    const valueNotEmpty = value || value == "0" ? true : false;
    if (rules.required && !valueNotEmpty) {
      return Promise.reject("必填项");
    }
    if (valueNotEmpty && !utils.numberReg.test(value)) {
      return Promise.reject("请输入数字");
    }
    return Promise.resolve();
  },

  /**
   * @description: 获取图片真实宽高
   * @param {String} url 图片地址
   * @param {Object} size 宽高
   */
  getImageSize: (url) => {
    return new Promise((resolve) => {
      const image = new Image();
      image.src = url;
      image.onload = function () {
        // console.log("图片原始高度", image.height);
        // console.log("图片原始宽度", image.width);
        resolve(image);
      };
    });
  },

  /**
   * @description: 动态获取keep-alive数组
   * @param {Array} list 路由表
   * @param {Array} result
   */
  getKeepAliveRoutes: (list, result) => {
    for (let item of list) {
      if (item.meta && item.meta.keepAlive === true) {
        result.push(item.name);
      }
      if (item.children && item.children.length) {
        utils.getKeepAliveRoutes(item.children, result);
      }
    }
  },

  /**
   * @description: 根据id获取当前菜单
   * @param {Array} list 路由表
   *  @param {Array} id 菜单id
   * @param {Object} current
   */
  getCurrentMenuById: (list, id) => {
    for (let menu of list) {
      if (menu.id == id) {
        return menu;
      }
      if (menu.children && menu.children.length) {
        const item = utils.getCurrentMenuById(menu.children, id);
        if (item) {
          return item;
        }
      }
    }
  },

  /**
   * @description: 复制内容到剪切板
   * @param {String} content
   */
  copyText: (content) => {
    let ele = document.createElement("textarea"); // 创建一个textarea标签
    ele.value = content; // 设置textarea的value值
    document.body.appendChild(ele); // 将textarea添加到body
    ele.select(); // 选择textarea的内容
  
    try {
      if (document.execCommand("copy")) { // 尝试执行复制命令
        notification.success({ message: "复制成功！", duration: 1 });
      } else {
        throw new Error("复制失败");
      }
    } catch (error) {
      console.error("复制失败：", error);
      //notification.error({ message: "复制失败，请手动复制", duration: 2 });
      throw new Error("复制失败");
    } finally {
      document.body.removeChild(ele); // 删除textarea标签
    }
  },

  /**
   * @description: 整数前面补0
   * @param {Number} num 待处理的整数
   * @param {Number} len 需要的长度
   */
  prefixInteger: (num, len) => {
    return (Array(len).join("0") + num).slice(-len);
  },

  /**
   * @description: 验证页面元素是否有权限操作或查看
   * @param {Array} action 待验证的action
   * @return {Boolean}
   */
  actionPermission: (action) => {
    if (!action || !Array.isArray(action) || action.length < 2) {
      notification.error({
        message: "错误",
        description: "v-action格式错误",
      });
    }
    const actions = store.getters.currentActions;
    if (actions) {
      for (let key in actions) {
        if (key == action[0]) {
          if (actions[key].includes(action[1])) {
            return true;
          }
        }
      }
    }
    return false;
  },

  /**
   * @description: 获取缓存姓名
   * @param {String} name
   */
  getStorageName: (name) => {
    return `${defaultSetting.from}_${defaultSetting.name}_${name}`;
  },

  /**
   * @description: 设置存储
   * @param {String}name 存储变量名
   * @param {*}info 存储内容
   * @param {Boolean} isCache 是否持久存储
   */
  setStorage: (name, info, isCache) => {
    const storageName = utils.getStorageName(name);
    if (isCache) {
      sessionStorage.setItem(storageName, info);
    } else {
      localStorage.setItem(storageName, info);
    }
  },
  /**
   * @description: 获取存储
   * @param {String}name 存储变量名
   * @param {Boolean} isCache 是否持久存储
   * @return {*} info 存储的内容
   */
  getStorage: (name, isCache) => {
    const storageName = utils.getStorageName(name);
    let info = null;
    if (isCache) {
      info = sessionStorage.getItem(storageName);
    } else {
      info = localStorage.getItem(storageName);
    }
    return info;
  },
  /**
   * @description: 移除存储
   * @param {String}name 存储变量名
   * @param {Boolean} isCache 是否持久存储
   */
  removeStorage: (name, isCache) => {
    const storageName = utils.getStorageName(name);
    if (isCache) {
      sessionStorage.removeItem(storageName);
    } else {
      localStorage.removeItem(storageName);
    }
  },
  /**
   * @description: 清空存储
   * @param {Boolean} isCache 是否是清空持久存储
   */
  clearStorage: (isCache) => {
    if (isCache) {
      sessionStorage.clear();
    } else {
      localStorage.clear();
    }
  },

  /**
   * @description: 打印数据
   * @param {*} msg 可选 打印的变量
   * @param {String}title  可选 打印的title
   */
  consoleInfo: (msg = "", title = "") => {
    console.group(
      `%c${new Date().toLocaleTimeString()} 【子应用-${defaultSetting.name}】`,
      `color:#426666;font-weight: bold;`
    );
    console.log(`${title} -- `, msg);
    console.groupEnd();
  },

  /**
   * @description: 判断当前是否是手机端
   */
  isMobile: () => {
    const mobile = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    return mobile ? true : false;
  },

  // 是否是开发环境
  isEnv: () => {
    if (process.env.NODE_ENV === "development") {
      return true;
    }
    return false;
  },
  /**
   * @description: 设置页面标题
   * @param {String} title
   */
  setDocumentTitle: (title) => {
    let isVersion = import.meta.env.ELECTRON
      ? `v${import.meta.env.VITE_APP_VERSION}`
      : "";
    store.dispatch("GetConfigInfo").then((config) => {
      if (config && config.basic && config.basic.system_name) {
        if(!title){
            return;
        }
        document.title = `${title} - ${L(
          config.basic.system_name
        )} ${isVersion}`.trim();
      } else {
        setTimeout(() => {
          utils.setDocumentTitle(title);
        }, 300);
        document.title = `${title} ${isVersion}`.trim();
        return;
      }
    });

    const ua = navigator.userAgent;
    // eslint-disable-next-line no-useless-escape
    const regex = /\bMicroMessenger\/([\d\.]+)/;
    if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
      const i = document.createElement("iframe");
      i.src = "/favicon.ico";
      i.style.display = "none";
      i.onload = function () {
        setTimeout(function () {
          i.remove();
        }, 9);
      };
      document.body.appendChild(i);
    }
  },

  /**
   * @description: 表单验证为手机号
   */
  phoneValidator: async (rule, value) => {
    if (!value) {
      if (rule.required) {
        return Promise.reject("必填项");
      }
      return Promise.resolve();
    }
    if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
      return Promise.reject("请输入正确的手机号码");
    }
    return Promise.resolve();
  },

  /**
   * @description: 数组处理成树 （递归）
   */
  transListToTreeData: (list, rootValue) => {
    var arr = [];
    list.forEach((item) => {
      if (item.parent_id == rootValue) {
        const children = utils.transListToTreeData(list, item.id);
        if (children.length) {
          item.children = children;
        } else {
          item.children = [];
        }
        arr.push(item);
      }
    });
    return arr;
  },

  /**
   * @description: 获取显示设备的dpi（每英寸像素数）
   */
  getDPI: () => {
    const div = document.createElement("div");
    div.style.cssText =
      "height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;";
    document.body.appendChild(div);
    const devicePixelRatio = window.devicePixelRatio || 1,
      dpi = div.offsetWidth * devicePixelRatio;
    return dpi;
  },
  /**
   *  获取路由参数
   */
  getQueryObj: (queryString) => {
    let queryParams = {};
    if (!queryString) {
      let query = location.href.split("?");
      if (query && query[1]) {
        queryString = query[1];
      }
    }
    if (queryString) {
      let queryArr = queryString.split("&");
      for (let item of queryArr) {
        const res = item.split("=");
        queryParams[res[0]] = res[1];
      }
    }
    return queryParams;
  },

  // 公共方法，给路由带上参数org_id
  addLinkOrgId: (type, path, query) => {
    let org_id = utils.getOrgId();
    let configInfo = store.getters.configInfo;
    let oem_org_id = null;
    if (configInfo && configInfo.basic && configInfo.basic.oem_org_id) {
      oem_org_id = configInfo.basic.oem_org_id;
    }
    // 路由跳转
    if (type == "router") {
      if (!query) {
        query = {};
      }
      if (org_id && !oem_org_id) {
        query.org_id = org_id;
      }
      console.log(type, path, query);
      return { path, query };
    } else if (type == "newWindow") {
      // 新窗口打开
      let params = "";
      if (query) {
        if (org_id && !oem_org_id) {
          params = "?org_id=" + org_id + "&" + query;
        } else {
          params = "?" + query;
        }
      } else {
        if (org_id && !oem_org_id) {
          params = "?org_id=" + org_id;
        }
      }
      // 拼接路由
      path =
        (process.env.NODE_ENV === "production" ? "/users" : "") + path + params;
      // 拼接域名
      path = location.origin + path;
      return { path };
    }
  },

  /**
   * @description: 获取路由参数
   */
  getUrlQuery: (variable, url) => {
    const query = url.split("?")[1];
    const queryObj = {};
    if (query) {
      const vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        queryObj[pair[0]] = pair[1];
        if (pair[0] == variable) {
          return pair[1];
        }
      }
    }
    return queryObj;
  },

  // user-token
  setUserToken: (token) => {
    return new Promise((resolve) => {
      localStorage.setItem("TOKEN_" + utils.getOrgId(), token);
      resolve();
    });
  },
  getUserToken: () => {
    return localStorage.getItem("TOKEN_" + utils.getOrgId());
  },
  clearUserToken: () => {
    localStorage.removeItem("TOKEN_" + utils.getOrgId());
    return;
  },

  /**
   * @description: AI相关
   */
  ...storage,

  // isLogin: () => {
  //   console.log(localStorage.getItem("TOKEN_" + utils.getOrgId()), '6666666666666666666');
  //   return store.getters.isLogin;
  // },
  isLogin: () => {
    const token = localStorage.getItem("AI_USER_TOKEN_" + utils.getOrgId());
    return Boolean(token); // 如果 token 存在，返回 true；否则返回 false
  },
  getUserInfo: () => {
    return store.dispatch("GetUserInfo");
  },
  checkLogin: () => {
    return new Promise((resolve) => {
      const token = localStorage.getItem("AI_USER_TOKEN_" + utils.getOrgId());
      if (Boolean(token)) {
        // if (store.getters.isLogin) {
        resolve(true);
      } else {
        resolve();
      }
    });
  },
  refreshWithInterval: (intervalInMinutes, durationInMinutes, cb) => {
    const interval = intervalInMinutes * 60 * 1000; // 将分钟转换为毫秒
    const stopTime = new Date().getTime() + durationInMinutes * 60 * 1000; // 当前时间 + 持续时间分钟数 * 60秒/分钟 * 1000毫秒/秒

    const timerId = setInterval(cb, interval);
    const timer = setTimeout(() => {
      clearInterval(timerId);
    }, stopTime - new Date().getTime());

    return () => {
      clearTimeout(timer);
      clearInterval(timerId);
    };
  },
  delay: (ms) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("");
      }, ms);
    });
  },
  isJSONStr: (str) => {
    if (/^\d+$/.test((str + "").trim())) {
      return false;
    }

    try {
      JSON.parse(str);
      return true;
    } catch (e) {
      return false;
    }
  },
  is: (val, type) => {
    return toString.call(val) === `[object ${type}]`;
  },
  isObject: (val) => {
    return val !== null && utils.is(val, "Object");
  },
  export2Word: (editorContent, filename = "") => {
    var html = `<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>${editorContent}</body></html>`;

    var blob = new Blob(["\ufeff", html], {
      type: "application/msword",
    });

    // Specify link url
    var url =
      "data:application/vnd.ms-word;charset=utf-8," + encodeURIComponent(html);

    // Specify file name
    filename = filename ? filename + ".docx" : "document.docx";

    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if (navigator.msSaveOrOpenBlob) {
      navigator.msSaveOrOpenBlob(blob, filename);
    } else {
      // Create a link to the file
      downloadLink.href = url;

      // Setting the file name
      downloadLink.download = filename;

      //triggering the function
      downloadLink.click();
    }

    document.body.removeChild(downloadLink);
  },

  // 验证手机号
  validatePhoneNumber: (phone) => {
    const phoneReg = /^1[3-9]\d{9}$/;
    // 使用正则表达式进行匹配
    const result = phoneReg.test(phone);
    return result;
  },

  //

  clearUserInfo: () => {
    localStorage.removeItem("AI_USER_INFO_" + localStorage.getItem("ORG_ID"));
  },

  parseRichText: (richText) => {
    const $ = cheerio.load(`<div>${richText}</div>`);
    const textContent = $("div").text();

    // 提取图片
    const imgs = $("img");
    const images = [];

    imgs.each((_, element) => {
      images.push($(element).attr("src"));
    });

    return {
      text: textContent,
      images,
    };
  },
  convertSecondsToMS: (milliseconds) => {
    const seconds = Math.floor((milliseconds / 1000) % 60); // 计算秒钟部分
    const minutes = Math.floor((milliseconds / (1000 * 60)) % 60); // 计算分钟部分

    return `${minutes >= 10 ? minutes : "0" + minutes}:${
      seconds >= 10 ? seconds : "0" + seconds
    }`;
  },
  removeEmoji: (str) => {
    return str
      .replace(
        /(?![*#0-9]+)[\p{Emoji}\p{Emoji_Modifier}\p{Emoji_Component}\p{Emoji_Modifier_Base}\p{Emoji_Presentation}]|Ⓐ|☭|✯|✙|ᛋ|卐|卍|࿕|࿖|࿗|࿘|ꖦ|☫|☤|❥|웃|유|☏|♚|▲|⚤|☒|♛|▼|♫|⌘|¡|♡|ღ|ツ|☼|❅|✎|✪|➳|✞|✿|✄|✫|★|/gu,
        ""
      )
      .replace(/(\n|\r|\t)/gm, "") // remove linebreaks
      .replace(
        /<(style|script|link|noscript).*?>.*?<\/(style|script|link|noscript)>/g,
        ""
      ) // remove css, js blocks
      .replace(/<!--.*?-->/g, "") // remove comments
      .replace(/<.*?>/g, "") // remove tags
      .replace(
        /[\s\!\@\#\$\%\^\&\*\(\)\_\+\-\=\{\}\[\]\:\"\;\'\<\>\?\,\.\/\|\\\`\~]+/g,
        " "
      );
  },
  /** 固定时间内只执行一次
   * @param {需要节流的时间} timeout
   * @param {需要节流执行的函数} fn
   * @returns
   */
  throttling: (timeout, fn) => {
    let _playing = null;
    return function () {
      let _arg = arguments;
      if (_playing) {
        return;
      }
      _playing = true;
      setTimeout(() => {
        fn.apply(this, _arg);
        _playing = false;
      }, timeout);
    };
  },
  /** 固定时间内频繁触发只执行最后一次
   * @param {防抖的时间} timeout
   * @param {需要防抖的函数} fn
   * @returns
   */
  debounce: (timeout, fn) => {
    let _time = null;
    return function () {
      let _arg = arguments;
      clearTimeout(_time);
      _time = setTimeout(() => {
        fn.apply(this, _arg);
      }, timeout);
    };
  },

  getVideoThumbnail: (videoUrl) => {
    return new Promise((resolve, reject) => {
      const video = document.createElement("video");

      video.src = videoUrl;
      video.crossOrigin = "anonymous"; // 确保视频允许跨域访问
      video.muted = true; // 有些浏览器需要将视频静音才能播放

      video.addEventListener("loadeddata", () => {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");

        // 设置 canvas 尺寸与视频相同
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 在 canvas 上绘制视频的第一帧
        context.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 将 canvas 转换为图片 URL
        const thumbnailUrl = canvas.toDataURL("image/png");

        console.log(
          thumbnailUrl,
          "将 canvas 转换为图片 URL将 canvas 转换为图片 URL将 canvas 转换为图片 URL将 canvas 转换为图片 URL"
        );
        resolve(thumbnailUrl);
      });

      video.addEventListener("error", (err) => {
        reject(err);
      });

      // 加载视频
      video.load();
    });
  },
  convertCookies(cookies) {
    if (!cookies || cookies.length === 0) {
      return ["", {}];
    }

    // 构建cookies字符串
    const cookiesStr = cookies
      .map((cookie) => `${cookie.name}=${cookie.value}`)
      .join(";");

    // 构建cookies字典对象
    const cookieDict = {};
    cookies.forEach((cookie) => {
      cookieDict[cookie.name] = cookie.value;
    });

    return [cookiesStr, cookieDict];
  },
  convertStrCookieToDict(cookieStr) {
    const cookieDict = {};
    if (!cookieStr) {
      return cookieDict;
    }

    const cookies = cookieStr.split(";");

    cookies.forEach((cookie) => {
      const trimmedCookie = cookie.trim();
      if (!trimmedCookie) {
        return;
      }
      const cookieParts = trimmedCookie.split("=");
      if (cookieParts.length !== 2) {
        return;
      }
      const cookieName = cookieParts[0];
      const cookieValue = cookieParts[1];
      cookieDict[cookieName] = cookieValue;
    });

    return cookieDict;
  },
  // 获取位置信息
  getLocation: () => {
    return new Promise((resolve, reject) => {
      if (navigator.geolocation) {
        // 获取用户的位置信息
        navigator.geolocation.getCurrentPosition(
          function (position) {
            // 成功获取位置信息后的回调函数
            const latitude = position.coords.latitude; // 纬度
            const longitude = position.coords.longitude; // 经度
            console.log("用户的位置信息：");
            console.log("纬度: " + latitude);
            console.log("经度: " + longitude);
            const data = {
              latitude,
              longitude,
            };
            resolve(data);
          },
          function (error) {
            // 处理获取位置信息失败的情况
            console.error("获取位置失败:", error.message);
            // message.error("获取位置失败");
            reject("位置获取失败");
          },
          {
            enableHighAccuracy: true, // 启用高精度定位（可选）
            timeout: 6000, // 超时时间（毫秒）
            maximumAge: 0, // 不使用缓存的位置信息
          }
        );
      } else {
        console.error("浏览器不支持 Geolocation API");
        // message.error("浏览器不支持位置获取");
        reject("位置获取失败");
      }
    });
  },

  // 获取消耗提示词(dom版本)
  useText: (params, endText='') => {
    // const useName = params.numberInfo.name
    // const textg =  `当前剩余${params.pointInfo?.current}${params.pointInfo.unit}${params.pointInfo.name},本次[${useName}]将消耗[${params.pointInfo.consumes}]${params.pointInfo.unit}${params.pointInfo.name},是否继续?`
    // return textg;

    const useName = params.numberInfo.name;
    const consumes = h(
      "span",
      { style: { color: "red" } },
      params.pointInfo.consumes
    ); // 使用 h 函数创建一个带颜色的 span
    const textg = `当前剩余${params.pointInfo.current}${params.pointInfo.unit}${params.pointInfo.name}，本次[${useName}]将消耗[`;
    // 这里将 consumes 放入到 h 函数中
    const content = h("span", {}, [
      textg,
      consumes,
      `]${params.pointInfo.unit}${params.pointInfo.name}，${endText || '是否继续?'} `,
    ]);
    return content;
  },
  // 提示版本
  useTips(params) {
    const useName = params.numberInfo.name;
    const consumes = h(
      "span",
      { style: { color: "red" } },
      params.pointInfo.consumes
    ); // 使用 h 函数创建一个带颜色的 span
    const textg = `当前剩余${params.pointInfo?.current}${params.pointInfo.unit}${params.pointInfo.name}，本次[${useName}]将消耗[${params.pointInfo.consumes}]${params.pointInfo.unit}${params.pointInfo.name}`;
    // 这里将 consumes 放入到 h 函数中
    const content = h("span", {}, [
      textg,
      consumes,
      `]${params.pointInfo.unit}${params.pointInfo.name}，是否继续?`,
    ]);
    return content;
  },
  kd(params = {}) {
    const { title = "提示", content = "", ok = null, res={} } = params;
    return new Promise((resolve, reject) => {
      // 如果消耗点数为 0 直接成功
      console.log(res,'提示接受到res');
      if (res?.pointInfo?.consumes <= 0) {
        resolve('ok')
        return
      }

       Modal.confirm({
        okText: "确定",
        cancelText: "取消",
        title,
        zIndex:9999,
        content: h("div", {}, [content]),
        onOk() {
          console.log("ok");
          resolve("ok");
        },
        onCancel() {
          reject("cancel");

        },
      });
    });
  },

  // 毫秒转为分钟向上取整
  getT(t) {
    const minutes = t / 60000; // 1分钟 = 60,000毫秒
    return Math.ceil(minutes); // 向上取整
  },

formatTimestamp : (timestamp) =>{
  // 如果是秒级时间戳，将其转为毫秒级
  if (timestamp.toString().length === 10) {
    timestamp *= 1000;
  }

  const date = new Date(timestamp);
  const padZero = (num) => (num < 10 ? `0${num}` : num);

  const year = date.getFullYear();
  const month = padZero(date.getMonth() + 1);
  const day = padZero(date.getDate());
  const hours = padZero(date.getHours());
  const minutes = padZero(date.getMinutes());
  const seconds = padZero(date.getSeconds());

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},
  // 文本弹窗
  md(params = {}) {
    const { title = "提示", content = "", zIndex=9999 } = params;
    return new Promise((resolve, reject) => {
      Modal.confirm({
        okText: "确定",
        cancelText: "取消",
        title,
        content,
        zIndex,
        onOk() {
          console.log("ok");
          resolve("ok");
        },
        onCancel() {
          reject("cancel");
        },
      });
    });
  },

  // 获取消耗规则提示文字
  ruleTips(params = {}) {
    const { res, key, endText='是否继续?' } = params;
    const target = res.result.content.find((ele) => ele.labelkey == key);
    if (target) {
      return `您当前${res.point_coin_alias}为${res.result.currentPoint}${res.point_coin_unit}，${target.label}消耗${target.value} ${endText}`;
    } else {
      return ''
    }
    
  },
  // 加载不出来的图片地址
  // errorImgSrc:'https://haowallpaper.com/link/common/file/previewFileImg/15459060196151616',
  // errorImgSrc:  ('https://v.kuaijing.cn' || "https://local.kuaijingai.com") +
  // "/public_web/static/" + '/images/workAi/shotstack/Invalid.png',
  errorImgSrc: imgErr,
  // errorImgSrc:  (defaultSetting.requestDomain || "https://local.kuaijingai.com") +
  // "/public_web/static/" + '/images/workAi/shotstack/Invalid.png',
  // 混剪图片加载失败
  imgError(e) {
    e.target.src = this.errorImgSrc
    // 修改 DOM 的样式，将 object-fit 设置为 scale-down
  // e.target.style.objectFit = 'scale-down';
  },

  textConfigGet,
  aiTextGet,
  getAllText,
  humanConfigGet,
  videoConverTextConfig,
  consumptionPointRule,
  oneclickPreviewNum,
  storyConfigGet,
};
export default utils;
